<template>
  <div>
    <nut-config-provider
      :theme-vars="{
        navbarTitleFont: '32rpx',
        navbarTitleFontWeight: '500',
        navbarTitleFontColor: '#000',
        navbarBoxShadow: 'none',
        navbarColor: '#000',
        navbarBackground: '#fff',
        checkboxMarginRight: '0'
      }">
      <uNavbar title="购物车" :is-back="false" fixed :custom-style="{ background: '#fff', zIndex: 999 }">
        <template #right>
          <span v-if="cartDetail && cartDetail.cartList.length" text-28rpx @click="isEdit = !isEdit" text-main-color>{{ isEdit ? '完成' : '编辑' }}</span>
        </template>
      </uNavbar>

      <!-- 购物车内容 -->
      <div v-if="isShow" p-16rpx pb-300rpx>
        <div v-if="cartDetail && cartDetail.cartList.length">
          <div v-for="(item, index) in cartDetail.cartList" mb-20rpx p-32rpx px-16rpx card :key="index">
            <div flex flex-a-c flex-j-sb mb-20rpx>
              <!-- 复选框、店铺名称 -->
              <div flex flex-a-c>
                <div>
                  <nut-checkbox v-model="item.checked" @tap.stop="checkedStore(item)"></nut-checkbox>
                </div>
                <div
                  @click="$navigateTo('/pages/goods/store/detail?id=' + item.storeId)"
                  text-30rpx
                  font-bold
                  flex
                  flex-a-c>
                  <nut-tag v-if="item.selfOperated" :custom-color="colors.themeColor" type="primary">自营</nut-tag>
                  <span ml-10rpx>
                    {{ item.storeName }}
                  </span>
                  <nut-icon size="14" name="rect-right"></nut-icon>
                </div>
              </div>
              <div
                text-main-color
                text-24rpx
                @click="$navigateTo('/pages/promotions/coupon/center?storeId=' + item.storeId)">
                领劵
              </div>
            </div>
            <!-- 商品 -->
            <div overflow-hidden>
              <nut-swipe-group lock>
                <nut-swipe
                  ref="goodsSwipe"
                  :name="goods.goodsSku.id"
                  v-for="(goods, gIndex) in item.skuList"
                  :key="gIndex">
                  <div :class="{ invalid: isInvalid(goods) }" flex py-24rpx flex-a-c>
                    <div flex flex-a-c>
                      <div>
                        <nut-checkbox
                          v-if="goods.invalid == 0 && !goods.errorMessage"
                          v-model="goods.checked"
                          @tap.stop="checkedGoods(goods)"></nut-checkbox>
                        <div v-else>失效</div>
                      </div>
                      <image
                        @click="
                          $navigateTo(
                            '/pages/goods/product/detail?skuId=' +
                              goods.goodsSku.id +
                              '&goodsId=' +
                              goods.goodsSku.goodsId
                          )
                        "
                        w-150rpx
                        h-150rpx
                        :src="goods.goodsSku.thumbnail"
                        w-140rpx
                        h-140rpx
                        rounded></image>
                    </div>
                    <div pl-16rpx flex-1 flex flex-col flex-j-sb>
                      <div flex flex-col flex-j-sb>
                        <div
                          @click="
                            $navigateTo(
                              '/pages/goods/product/detail?skuId=' +
                                goods.goodsSku.id +
                                '&goodsId=' +
                                goods.goodsSku.goodsId
                            )
                          ">
                          <!-- 商品名称 -->
                          <div text-28rpx class="goods-name">
                            {{ goods.goodsSku.goodsName }}
                          </div>
                          <!-- 规格 -->
                          <div my-10rpx color-warmGray text-24rpx>
                            {{ goods.goodsSku.simpleSpecs || '' }}
                          </div>
                        </div>

                        <!-- 价格 -->
                        <div h-60rpx line-height-60rpx flex flex-a-c flex-j-sb>
                          <div text-30rpx font-bold text-main-color v-if="goods.goodsSku.price">
                            {{ unitPrice(goods.goodsSku.price, '￥') }}
                          </div>
                          <div>
                            <nut-input-number
                              button-size="24"
                              @change="changeSku($event, goods)"
                              :min="1"
                              :max="999"
                              v-model="goods.num" />
                          </div>
                        </div>
                        <div style="margin-left: 20rpx" v-if="!goods.checked && goods.errorMessage">
                          {{ goods.errorMessage }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <template #right>
                    <nut-button
                      shape="square"
                      style="height: 100%"
                      type="primary"
                      @click="deleteCurrentClickGoods(goods, gIndex)">
                      删除
                    </nut-button>
                  </template>
                </nut-swipe>
              </nut-swipe-group>
            </div>
          </div>
        </div>
        <div v-else mt-100rpx>
          <empty>
            <div text-main-color mt-20rpx @click="backToHome">随便逛逛</div>
          </empty>
        </div>
        <div v-if="cartDetail.priceDetailDTO" fixed position-fixed bottom-60px class="tabbar" >
          <div flex flex-a-c px-36rpx>
            <nut-checkbox @tap.stop="checked" v-model="isCheckout">全选</nut-checkbox>
            <div ml-20rpx>
              总计:
              <span font-bold>{{ unitPrice(cartDetail.priceDetailDTO.flowPrice, '￥') }}</span>
            </div>
          </div>
          <div px-36rpx>
            <nut-button v-if="!isEdit" @click="billOrder" type="primary">去结算</nut-button>
            <nut-button v-else :loading="loading" @click="deleteAllChecked" type="primary">全部删除</nut-button>
          </div>
        </div>
      </div>
    </nut-config-provider>

    <nut-toast ref="toastRef" />
  </div>
  <shop-tabbar></shop-tabbar>
</template>

<script setup lang="ts">
import uNavbar from '@/components/navbar/index.vue'
import { changeSkuNum, checkAll, checkStore, checkedSku, deleteSkuItem, getCartsALL } from '@/api/trade'
import empty from '@/components/empty/index.vue'
import { colors } from '@/constants/injection-key'
import { unitPrice } from '@/utils/filters'
import { onShow } from '@dcloudio/uni-app'
import type { ToastInst } from 'nutui-uniapp'
import { isLogin, forceLogin } from '@/utils/filters';

const loading = ref(false)
const isCheckout = ref(false)
const isEdit = ref(false) // 是否编辑
const isShow = ref(false) // 是否展示
const goodsSwipe = ref<any>(null)
const cartDetail = ref<any>('') // 购物车详情
const toastRef = ref<ToastInst>() // toast

// 计算属性判断是否有上一页, 是否为navigateTo进来的
const isBack = computed(() => {
  const pages = getCurrentPages()
  return pages.length > 1
})

function isInvalid(val: any) {
  //是否无效商品/没库存商品
  if (val.invalid === 1 || (!val.checked && val.errorMessage)) {
    return true
  } else {
    return false
  }
}

function billOrder() {
  const ids: any = isCheckedAll()
  if (ids.length) {
    uni.navigateTo({
      url: '/pages/mine/order/fillorder?way=CART'
    })
  } else {
    uni.showToast({
      title: '您还没有选择商品',
      icon: 'none'
    })
  }
}

function isCheckedAll() {
  return cartDetail.value.skuList.filter((item: any) => item.checked).map((item: any) => item.goodsSku.id)
}

async function deleteAllChecked() {
  const ids: any = isCheckedAll()
  if (ids.length) {
    loading.value = true
    const res = await deleteSkuItem(ids)
    if (res.data.success) {
      loading.value = false
      fetchCartList()
    }
  } else {
    if (!cartDetail.value.skuList.length) {
      uni.showToast({
        title: '当前购物车暂无商品',
        icon: 'none'
      })
      return
    }

    uni.showToast({
      title: '请选择要删除的商品',
      icon: 'none'
    })
  }
}

// 是否展示加载框 true 加载
function enableLoading(enable: boolean) {
  enable
    ? toastRef.value?.showToast['loading']('加载中', {
        cover: true,
        duration: 0
      })
    : toastRef.value?.hideToast()
}
// 删除当前点击选中的商品
async function deleteCurrentClickGoods(goods: any, index: number) {
  enableLoading(true)
  const res = await deleteSkuItem(goods.goodsSku.id)
  enableLoading(false)
  if (res.data.success) {
    goodsSwipe.value[index]?.close()
    fetchCartList()
  }
}

const backToHome = () => {
  uni.switchTab({
    url: '/pages/mall'
  })
}
// 初始化
function init() {
  fetchCartList()
}
// 全选/取消全选
async function checked() {
  const res = await checkAll(isCheckout.value)
  if (res.data.success) {
    fetchCartList()
  }
}

// 修改商品数量
async function changeSku($event: any, goods: any) {
  enableLoading(true)
  const res = await changeSkuNum(goods.goodsSku.id, $event)
  enableLoading(false)
  if (res.data.success) {
    fetchCartList()
  }
}

// 选择商品/取消选择
async function checkedGoods(val: any) {
  const res = await checkedSku(val.goodsSku.id, val.checked)
  if (res.data.success) {
    fetchCartList()
  }
}

// 全选店铺/取消全选
async function checkedStore(val: any) {
  const res = await checkStore(val.storeId, val.checked)
  if (res.data.success) {
    fetchCartList()
  }
}
// 获取购物车详情
async function fetchCartList() {
  enableLoading(true)
  const res = await getCartsALL()
  enableLoading(false)
  isShow.value = true
  if (res.data.success) {
    cartDetail.value = res.data.result
    // 判断当前购物车是否有选中的商品
    if (res.data.result.cartList) {
      let isCheckoutAll = true // 是否全选
      res.data.result.cartList.forEach((item: any) => {
        item.skuList.forEach((sku: any) => {
          if (!sku.checked) {
            isCheckoutAll = false
          }
          // 判断是否有拼团活动
          item.skuList &&
            item.skuList.forEach((sku: any) => {
              if (!sku.checked) {
                isCheckoutAll = false
              }
              if (Object.keys(sku.promotionMap).length != 0) {
                Object.keys(sku.promotionMap).forEach((pro, proIndex) => {
                  pro = pro.split('-')[0]
                  if (pro == 'PINTUAN') {
                    Object.keys(sku.promotionMap).splice(proIndex, 1)
                  }
                })
              }
            })
        })
      })
      isCheckout.value = isCheckoutAll
    }
  }
}

onShow(() => {
  forceLogin()
  if (!isLogin("auth")) {
    return
  }
  init()
})
</script>

<style scoped lang="scss">
.goods-name {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.invalid {
  filter: grayscale(1);
}

.tabbar {
  justify-content: space-between;
  position: fixed;
  bottom: calc(60px + env(safe-area-inset-bottom));
  left: 0;
  border-top: 1px solid #ededed;
  display: flex;
  height: 57px;
  overflow: hidden;
  align-items: center;
  width: 100%;
  background: white;
  color: #333;
  z-index: 99;
  
}

::v-deep .nut-swipe__right .nut-button {
  height: 100%;
  margin-left: 2rpx;
}
</style>
